<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>消息</title>
    <base href="/websocket/" />
    <!--the css for jquery.mCustomScrollbar-->
    <link rel="stylesheet" href="lib/jquery-mCustomScrollbar/css/jquery.mCustomScrollbar.min.css"/>
    <!--the css for this plugin-->
    <link rel="stylesheet" href="lib/jquery-emoji/css/jquery.emoji.css"/>
    <link rel="stylesheet" href="/webjars/layui/2.5.6/css/layui.css"/>
    <link rel="stylesheet" href="css/index.css">
</head>
<body>
<!-- 聊天盒子 -->
<div class="container  invisible" style="display: block">
    <!-- 左侧用户列表 -->
    <div class="user-list">
        <div class="header">
            <div class="avatar">
                <img th:src="@{/images/}+${#httpSession.getAttribute('user').img}" style="border-radius: 50%" alt="" id="fromImg" class="img avatar_url">
            </div>
            <div class="info">
                <input type="hidden" th:value="${#httpSession.getAttribute('user').id}" id="fromId"/>
                <h3 th:text="${#httpSession.getAttribute('user').username}" class="username" ></h3>
            </div>
        </div>
        <div class="title">
            <h3>用户列表</h3>
        </div>
        <!-- <div>
          <li class="user active">
            <div class="avatar"><img src="images/avatar01.jpg" alt=""></div>
            <div class="name">群聊</div>
          </li>
        </div> -->
        <ul>
            <li th:each="user : ${userList}" class="user" style="cursor: pointer">
                <input type="hidden" th:value="${user.id}" name="goodUser"/>
                <div class="avatar"><img th:src="@{/images/}+${user.img}" alt="" style="border-radius: 50%"></div>
                <div class="name"  th:text="${user.username}" th:value="${user.id}" th:style="'color:'+${user.style}">群聊</div>
            </li>
        </ul>
    </div>
    <!-- 聊天主窗口 -->
    <div class="box">
        <div class="box-hd">
            <!-- <div id="chatName"></div> -->
<!--            <h3 id="chatName">群聊(<span id="userCount" th:text="${#httpSession.getAttribute('onlineUser').size()+1}"></span>)</h3>-->
             <h3 id="chatName">群聊</h3>
        </div>
        <div class="box-bd" data="*" th:utext="${hypertext}"></div>
<!--        <div class="box-bd" data="*">-->

<!--        </div>-->
<!--        [[${hypertext}]]-->
<!--        <div class="box-bd" data="*">-->
<!--             <div class="system">-->
<!--              <p class="message_system">-->
<!--                <span class="content">往事随风 加入群聊</span>-->
<!--              </p>-->
<!--            </div>-->
<!--            <div class="message-box">-->
<!--              <div class="my message">-->
<!--                <img src="images/avatar02.jpg" alt="" class="avatar">-->
<!--                <div class="content">-->
<!--                  <div class="bubble">-->
<!--                    <div class="bubble_cont">在干嘛</div>-->
<!--                  </div>-->
<!--                </div>-->
<!--              </div>-->
<!--            </div>-->
<!--            <div class="message-box">-->
<!--              <div class="other message">-->
<!--                <img src="images/avatar02.jpg" alt="" class="avatar">-->
<!--                <div class="nickname">小美士大夫撒旦发送到发发呆撒旦</div>-->
<!--                <div class="content">-->
<!--                  <div class="bubble">-->
<!--                    <div class="bubble_cont">在干嘛</div>-->
<!--                  </div>-->
<!--                </div>-->
<!--              </div>-->
<!--            </div> -->
<!--        </div>-->
        <div class="box-bd"  th:each="user : ${#httpSession.getAttribute('onlineUser')}" th:data="${user.id}" style="display: none;"></div>
        <!-- 聊天窗口底部 -->
        <div class="box-ft">
            <!-- 工具栏 -->
            <div class="toolbar">
                <a class="face" href="javascript:;" title="表情"></a>
                <!-- <a class="screen-cut" href="javascript:;" title="暂不支持截屏"></a> -->
                <a href="javascript:;" title="图片" class="file">
                    <form id="myImge">
                    <label for="file"></label><input onchange="commitImg()" type="file" name="file" id="file" style="display:none;">
                    </form>
                </a>
            </div>
            <!-- 内容输入区 -->
            <div class="content">
                <!-- div添加contenteditable即可编辑 -->
                <div name="" id="content" class="text" contenteditable></div>
            </div>
            <!-- 发送按钮 -->
            <div class="action">
                <span class="desc">按下Ctrl+Enter发送</span>
                <a class="btn-send" id="btn-send" href="javascript:;" onclick="send('msg')">发送</a>
            </div>
        </div>
    </div>
</div>

<script src="/webjars/jquery/3.5.1/jquery.js"></script>
<script src="lib/jquery-mCustomScrollbar/script/jquery.mCustomScrollbar.min.js"></script>
<script src="lib/jquery-emoji/js/jquery.emoji.min.js"></script>
<script src="/webjars/layui/2.5.6/layui.js"></script>

<script>
    $(function () {
        $(document).keydown(function(event){
            if(event.keyCode==13){
                $("#btn-send").click();
            }
        });
    })

    var toId = "*";
    var webSocket = null;
    var url = null;


    function Id(id){
        return document.getElementById(id);
    }
    //获取input[file]图片的url Important
    function getFileUrl(fileId) {
        var url;
        var file = Id(fileId);
        var agent = navigator.userAgent;
        if (agent.indexOf("MSIE")>=1) {
            url = file.value;
        } else if(agent.indexOf("Firefox")>0) {
            url = window.URL.createObjectURL(file.files.item(0));
        } else if(agent.indexOf("Chrome")>0) {
            url = window.URL.createObjectURL(file.files.item(0));
        }
        return url;
    }
    function  commitImg() {
        var formData = new FormData($("#myImge")[0]);
        $.ajax({
            type: "post",
            url: "/weCantUpload",
            data: formData,
            contentType: false,//告诉客户端不要设置Content-Type 请求头部
            processData: false,//告诉客户端不处理过程数据
            async:false,//关闭异步
            success: function (data) {//完成后的事件
                console.log(data);
                $("#content").append("<img id='sendImage' src='/images/message/"+data.msg+"' style='width: 80px'/>");
            },
            error: function (error) {//出现错误时的事件
                // layer.msg("上传图片失败");
                console.log("异常l"+error);
            }
        });
        send("msg");
    }
    /**
     * 创建连接
     */
    function connect(urlPath) {

        /**
         * 判断协议 - http or https
         */
        url = isUrl(urlPath);

        /**
         * 显示信息
         */
        console.log("链接url为:" + url);

        /**
         * 建立连接
         */
        webSocket = new WebSocket(url);

        /**
         * 连接成功
         */
        webSocket.onopen = function (socket){
            console.log('Info: 连接成功.');
            send("sys");
            // console.log(socket);
            // console.log(socket.data);
        };

        /**
         * 连接失败
         */
        webSocket.onerror = function () {
            console.log('Info: 连接失败.');

        };

        /**
         * 连接断开
         */
        webSocket.onclose = function (event) {
            console.log('Info: 连接断开.');
            send("out");
            console.log(event.data);
        };

        /**
         * 来自服务器的消息
         */
        webSocket.onmessage = function (event) {
            var data = JSON.parse(event.data);
            // showText(data['messageDate'] + '<br/> 发送人:'+data['fromName'] + data['messageText']);
            showText(data);
        };

    }
    connect("/ListMap/websocket")
    /**
     * 发送消息
     */
    function send(type) {
        // if($("#content").html().trim()==""){return;}
        // layui.use(['jquery'],function () {
        //     var $=layui.jquery;

            // }
        // })

        // 判断是否已连接
        if (webSocket != null) {
            // 新建data对象，并规定属性名与相应的值
            var data = {};
            // 发送者ID
            data['fromId'] =  $("#fromId").val();
            // 发送者Name
            data['fromName'] = $(".username").text();
            data['fromImg'] = $("#fromImg").attr("src");
            // 接收者ID - userSocketSessionMap - key
            // 注意 - NZ1 代表是第一个连接人的key - 测试
            // 消息发送的也是给第一个连接者
            data['toId'] ="*";
            data['type'] =type;
            data['hypertext'] =$(".box-bd").html();
            // 发送的消息
            data['messageText'] = $("#content").html();
            // 将对象封装成JSON后发送至服务器
            webSocket.send(JSON.stringify(data));
            // 显示消息
            console.log('Sent: ' + data['messageText']);
        } else {
            console.log('Send: 连接未建立，请连接。');
        }

    }
    // 表示底部滚动到可视区
    function scrollIntoView(){
        $('.box-bd').children(":last").get(0).scrollIntoView(false)
    }
    /**
     * 显示文本
     * @param message
     */
    function showText(data) {
        // var a=data['fromId'];
        // var b=data['toId'];
        console.log(data);
        if(data['type']=="sys"){
            $("[class=name][value='"+data['fromId']+"']").css("color","red");
            $(".box-bd").append('<div class="system">\n' +
                '              <p class="message_system">\n' +
                '                <span class="content">'+data["fromName"]+' 加入了聊天室</span>\n' +
                '              </p><br>\n' +
                '            </div>')
            scrollIntoView()
            return;
        }
        if(data['type']=="out"){
            $(".box-bd").append('<div class="system">\n' +
                '              <p class="message_system">\n' +
                '                <span class="content">'+data["fromName"]+' 退出了聊天室</span>\n' +
                '              </p>\n' +
                '            </div>')
            scrollIntoView()
            return;
        }
        if(data['fromId']==$("#fromId").val()){
            console.log("是自己的消息");
            $(".box-bd").append('<div class="message-box">\n' +
                '              <div class="my message">\n' +
                '                <img src="'+data["fromImg"]+'" alt="" class="avatar" style="border-radius: 50%" >\n' +
                '                <div class="content">\n' +
                '                  <div class="bubble">\n' +
                '                    <div class="bubble_cont">'+data["messageText"]+'</div>\n' +
                '                  </div>\n' +
                '                </div>\n' +
                '              </div>\n' +
                '            </div>')
        }else{
            $(".box-bd").append('<div class="message-box">\n' +
                '              <div class="other message">\n' +
                '                <img src="'+data["fromImg"]+'" alt="" class="avatar" style="border-radius: 50%" >\n' +
                '                <div class="nickname">'+data["fromName"]+'</div>\n' +
                '                <div class="content">\n' +
                '                  <div class="bubble">\n' +
                '                    <div class="bubble_cont">'+data["messageText"]+'</div>\n' +
                '                  </div>\n' +
                '                </div>\n' +
                '              </div>\n' +
                '            </div>')
        }
        $("#content").html('');
        $("#file").val('');
        scrollIntoView();
        // var console = $('#console');
        //
        // $(console).html($(console).html() + "<br/>" + message);

    }

    /**
     * 判断协议 - http or https
     */
    function isUrl(urlPath) {

        if (window.location.protocol == 'http:') {
            return 'ws://' + window.location.host + urlPath;
        } else {
            return 'wss://' + window.location.host + urlPath;
        }

    }


    // 初始化jquery-emoji插件
    $('.face').on('click', function () {
        $('#content').emoji({
            button: '.face',
            showTab: false,
            animation: 'slide',
            position: 'topRight',
            icons: [{
                name: 'QQ表情',
                path: 'lib/jquery-emoji/img/qq/',
                maxNum: 91,
                excludeNums: [41, 45, 54],
                file: '.gif'
            }]
        })
    })
</script>
</body>
</html>